package com.fasteat.netty.handler;

import com.fasteat.util.ServiceRecord;
import com.fasteat.util.UserChannelMap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;


/**
 * 当读写空闲时关闭连接
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if(idleStateEvent.state() == IdleState.ALL_IDLE){
                //删除对应的映射
                String removedUserId = UserChannelMap.remove(ctx.channel().id());
                //判断是否为客服，是则删除对应记录
                if(ServiceRecord.isService(removedUserId)){
                    ServiceRecord.remove(removedUserId);
                }
            }
        }
    }
}
